var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { adminsModel } = require('../dao/models/adminsModel');
const assert = require('http-assert');


const { getSelfAdmin, addAdmins, getAdmins, updateAdmins } = require('../service/adminsService');
/* GET home page. */
router.post('/', async function(req, res, next) {
    //用小写获取
    const token = String(req.headers.authorization || '').split(' ').pop();
    // if (!token) {
    //     return res.status(401).send({
    //         message: '请先登录'
    //     });
    // }
    assert(token, 401, '请先登录');

    //校验token
    const { id } = jwt.verify(token, 'zhangsan');
    // if (!id) {
    //     return res.status(401).send({
    //         message: '请先登录'
    //     });
    // }
    assert(id, 401, '请先登录');
    req.admin = await adminsModel.findById(id);
    // if (!req.admin) {
    //     return res.status(401).send({
    //         message: '请先登录'
    //     });
    // }

    assert(req.admin, 401, '请先登录');
    await next();
}, async function(req, res, next) {
    res.send({ power: req.admin.power });
});

router.post('/getSelfAdmin', async function(req, res, next) {
    //用小写获取
    const token = String(req.headers.authorization || '').split(' ').pop();
    //校验token
    const { id } = jwt.verify(token, 'zhangsan');
    req.admin = await adminsModel.findById(id);
    await next();
}, async function(req, res, next) {
    const result = await getSelfAdmin(req.admin._id);
    res.send(result);
});
router.post('/addAdmins', async function(req, res, next) {
    await addAdmins(req.body);
    res.send({ status: 1 });
});
router.get('/getAdmins', async function(req, res, next) {
    const result = await getAdmins();
    res.send(result);
});
router.put('/addAdmins/:id', async function(req, res, next) {
    const result = await updateAdmins(req.params.id, req.body);
    res.send(result);
});
router.get('/addAdmins/:id', async function(req, res, next) {
    const result = await getSelfAdmin(req.params.id);
    res.send(result);
});

router.post('/login', async function(req, res, next) {
    const { account, password } = req.body;
    //1、根据用户名找用户

    const admin = await adminsModel.findOne({ account });

    assert(admin, 422, '用户不存在');
    // assert(admin.state == 2, 422, '账户被冻结，不可操作');

    // if (!admin) {
    //     // 设定一个状态码，让人知道不是200
    //     return res.status(422).send({
    //         message: '用户不存在'
    //     });
    // }
    if (admin.state == 2) {
        return res.status(422).send({
            message: '账户被冻结，不可操作'
        });
    }

    //2、校验密码
    const isValid = require('bcrypt').compareSync(password, admin.password);
    assert(isValid, 422, '密码错误');
    // if (!isValid) {
    //     return res.status(422).send({
    //         message: '密码错误'
    //     });
    // }

    //3、返回token
    //服务端给个密钥
    const token = jwt.sign({ id: admin._id }, 'zhangsan');

    res.send({ token, id: admin._id });
});

module.exports = router;